package com.ymy.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ymy.entity.TbSpeedkill;
import com.ymy.mapper.SpeedkillMapper;
import com.ymy.util.DateUtil;
import com.ymy.util.RedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author slient
 */
@Component
public class LoadSpeedkillGoods {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    SpeedkillMapper speedkillMapper;

    @Scheduled(cron = "0/5 * * * * ? ") //每隔5秒钟执行一次任务
    public void load(){
        //查询
        //查询是是时间段
        List<Date> dateList = DateUtil.getDateMenus();
        for (Date start : dateList) {
            QueryWrapper<TbSpeedkill> wrapper = new QueryWrapper<>();
            wrapper.eq("speed_starttime",start);//起始时间条件，大于
            wrapper.eq("speed_endtime",DateUtil.addDateHour(start,2));//小于
            wrapper.eq("speed_checkstatus",1);//秒杀的商品需要审核通过，状态为1
            //条件：这些商品不存在redis中？？
            Set set = redisTemplate.opsForHash().keys(RedisKey.SPEED_KILL_GOODS + DateUtil.date2Str(start));
            if (set != null && set.size()>0){
                wrapper.notIn("goods_id",set);
            }
            List<TbSpeedkill> tbSpeedkills = speedkillMapper.selectList(wrapper);
            for (TbSpeedkill tbSpeedkill : tbSpeedkills) {
                //redis中的时间段内的秒杀商品
                redisTemplate.boundHashOps(RedisKey.SPEED_KILL_GOODS + DateUtil.date2Str(start))
                        .put(tbSpeedkill.getGoodsId().toString(),tbSpeedkill);
                //库存--tbSpeedkill -- speedStock 属性
                redisTemplate.boundValueOps(RedisKey.SPEED_KILL_GOODSTOCK + tbSpeedkill.getGoodsId().toString())
                        .set(tbSpeedkill.getSpeedStock());
            }
        }
        //redis中是否存在指定的key
        //查库
    }
}















